package study.saas.common.util.http;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * HTTP工具类
 */
public class HttpUtils {

    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 将map转换成url
     *
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String getUrlParamsByMap(Map<String, String> map)
            throws UnsupportedEncodingException {
        if (map == null) {
            return "";
        }
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            sb.append(entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8"));
            sb.append("&");
        }
        String s = sb.toString();
        if (s.endsWith("&")) {
            s = StringUtils.substringBeforeLast(s, "&");
        }
        return s;
    }

    /**
     * 连接发送服务器的时间,3秒
     */
    private static final int CONNECT_TIMEOUT = 60 * 1000;
    /**
     * 等待发送服务器返回的时间,假设通道商最慢也能在60分钟之内返回
     */
    private static final int READ_TIMEOUT = 60 * 1000;


    public static String sendHandleGet(String url, Map<String, String> params, Map<String, String> headers) throws IOException {
        String responseBody = null;
        //重试机制可能需要改善
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String paramString = getUrlParamsByMap(params);
        if (StringUtils.isNotEmpty(paramString)) {
            url = url + "?" + paramString;
        }
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "application/json;charset=utf-8");
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpGet.setHeader(header.getKey(), header.getValue());
            }
        }
        httpGet.setConfig(RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(READ_TIMEOUT).build());
        CloseableHttpResponse response = null;
        try {
            long t1 = System.currentTimeMillis();
            log.info("[{}],HTTP请求[{}],header[{}]", url, "GET", headers);
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            responseBody = EntityUtils.toString(entity, "UTF-8");
            long t2 = System.currentTimeMillis();
            log.info("[{}],HTTP请求[{}],code[{}],返回结果[{}],响应时间:[{}]", url, statusCode, "GET", responseBody, t2 - t1);
        } catch (Exception e) {
            log.error("[{}]发送流程异常", url, e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
        return responseBody;
    }

    /**
     * post发送的接口
     */
    public static String sendHandlePost(String url, String body, Map<String, String> params, Map<String, String> headers) throws IOException {
        long start = System.currentTimeMillis();
        String responseBody = null;
        //重试机制可能需要改善
        String paramString = getUrlParamsByMap(params);
        if (StringUtils.isNotEmpty(paramString)) {
            url = url + "?" + paramString;
        }
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        post.setConfig(RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(READ_TIMEOUT).build());
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Accept", "application/json");
        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                post.setHeader(header.getKey(), header.getValue());
            }
        }
        StringEntity codeEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
        post.setEntity(codeEntity);

        CloseableHttpResponse response = null;
        try {
            long t1 = System.currentTimeMillis();
            post.setEntity(codeEntity);
            log.info("[{}],HTTP请求[{}],header[{}],body[{}]", url, "POST", headers, body);
            response = httpClient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            responseBody = EntityUtils.toString(entity, "UTF-8");
            long t2 = System.currentTimeMillis();
            log.info("[{}],HTTP请求[{}],code[{}],返回结果[{}],响应时间:[{}]", url, statusCode, "POST", responseBody, t2 - t1);
        } catch (Exception e) {
            log.error("[{}]发送流程异常", url, e);
        } finally {
            if (response != null) {
                response.close();
            }
            httpClient.close();
        }
        return responseBody;
    }

}
